<template>
  <div>
    <el-input v-model="username" disabled :width="width">
      <el-button slot="append" icon="el-icon-s-grid" @click="openModal" />
    </el-input>

    <user-modal ref="userModal" :value="value" @ok="handleOK" />
  </div>
</template>

<script>
import userModal from '@/components/popsoft/CommonSelect/User/Single/Modal'

export default {
  name: 'UserSingleSelect',
  components: {
    userModal
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    width: {
      type: Number,
      default: 500,
      required: false
    },
    value: {
      type: String,
      default: '',
      required: false
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    // 绑定对象，用于父组件动态创建多个选择框的情况
    refObject: {
      type: Object,
      default: null,
      required: false
    }

  },
  data() {
    return {
      visible: false,
      username: ''
    }
  },
  watch: {
    value: {
      immediate: true,
      handler: 'handleValue'
    }
  },
  methods: {
    openModal() {
      this.$refs.userModal.show()
    },
    handleValue() {
      if (this.value) {
        this.$api.system.user.get(this.value)
          .then((res) => {
            this.username = res.data.name
          })
      }
    },
    handleOK(user) {
      // 更新父组件绑定值
      this.$emit('change', user.id)
      // 将用户对象传递回父组件，用于父组件灵活使用，例如获取账号、姓名等
      this.$emit('changeSelect', user, this.refObject)
    }
  }
}
</script>

<style scoped>
</style>
